package com.example.baselibrary.util;

import android.app.ActivityManager;
import android.content.Context;

import java.util.List;

/**
 * @author: NPF
 * @date: 2018/4/12.
 */
public class LKAppUtil {


    private static LKAppUtil mInstance;

    private LKAppUtil() {
    }

    public static LKAppUtil getInstance() {
        if (null == mInstance) {
            synchronized (LKAppUtil.class) {
                if (null == mInstance) {
                    mInstance = new LKAppUtil();
                }
            }
        }
        return mInstance;
    }


    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断程序是否正在后台运行
     *
     * @param context
     * @return
     */
    public boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        if (activityManager == null) return false;
        List<ActivityManager.RunningTaskInfo> processList = activityManager.getRunningTasks(100);
        if (processList == null)
            return false;
        for (ActivityManager.RunningTaskInfo info : processList) {
            if (info.topActivity.getPackageName().startsWith(packageName)) {
                return true;
            }
        }
        return false;
    }
}
